package com.api.gbhg.liuwenbo.action;

import com.api.gbhg.liuwenbo.dao.TreeStuctureDBUtil;
import com.api.gbhg.liuwenbo.dao.VerificationDBUtil;
import com.api.gbhg.liwenjun.VersionFlowUtil;
import com.google.common.base.Joiner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/**
 * 金额扣减Action
 */
public class AmountDeduction implements Action {

    private static final Logger logger = LoggerFactory.getLogger("gbhg");

    private static String YJ ;
    private static String XJ ;

    static{
//            Properties prop=new Properties();
//            prop.load(new InputStreamReader(AmountDeduction.class.getResourceAsStream("../conf/Verification.properties")));
//            YJ = prop.getProperty("yj");
//            XJ = prop.getProperty("xj");
        BaseBean baseBean = new BaseBean();
        YJ = baseBean.getPropValue("Verification","yj");
        XJ = baseBean.getPropValue("Verification","xj");
    }
    @Override
    public String execute(RequestInfo requestInfo) {
        logger.info("进入预算编制金额扣减action-----------");
        int mainTableId = VersionFlowUtil.getFlowTableLableId(requestInfo.getWorkflowid());//获取formid 例如：-83
        String mainTabName = AmountVerification.getMainTableName(mainTableId);//获取主表名
        Integer dw = AmountVerification.getwofkflowDw(mainTabName, requestInfo.getRequestid());

        List<String> flowDetailTableNames = AmountVerification.getDetailTables(mainTableId);//获取明细表名称

        String flowTableName = VersionFlowUtil.getFlowTableName(requestInfo.getWorkflowid());//获取表名

        String id = AmountVerification.getIdByTable(flowTableName, requestInfo.getRequestid()); //获取流程当前id

        //数据转换
        Map<String, Object> dnData = AmountVerification.getDataBydt(flowDetailTableNames.get(0), id,"dfczbkxmdnys");

        Map<String, Object> snData = AmountVerification.getDataBydt(flowDetailTableNames.get(1), id,"dfczbkxmsnjz");

        RecordSetTrans rst = new RecordSetTrans();
        rst.setAutoCommit(false);
        boolean s1 = false;
        boolean s2 = false;
        boolean sql1 = false;
        boolean sql2 = false;
        boolean sql3 = false;
        boolean sql4 = false;

        StringBuffer fzydnzc = new StringBuffer();//非中央当年支出 -
        StringBuffer fzydnzc2 = new StringBuffer();//非中央当年支出    +
        StringBuffer fzydnzc3 = new StringBuffer();//非中央当年支出

        StringBuffer fzysnzc = new StringBuffer();//非中央上年支出
        StringBuffer fzysnzc2 = new StringBuffer();//非中央上年支出

        StringBuffer fzydnxmzc = new StringBuffer();//非中央当年项目支出 -
        StringBuffer fzydnxmzc2 = new StringBuffer();//非中央当年项目支出
        StringBuffer fzydnxmzc3 = new StringBuffer();//非中央当年项目支出

        StringBuffer fzysnxmzc = new StringBuffer();//非中央上年项目支出
        StringBuffer fzysnxmzc2 = new StringBuffer();//非中央上年项目支出

        StringBuffer zydnzckm = new StringBuffer();//中央当年支出科目
        StringBuffer zydnzckm2 = new StringBuffer();//中央当年支出科目
        StringBuffer zydnzckm3 = new StringBuffer();//中央当年支出科目

        StringBuffer zydnzcxj = new StringBuffer();//中央当年支出下级
        StringBuffer zydnzcxj2 = new StringBuffer();//中央当年支出下级
        StringBuffer zydnzcxj3 = new StringBuffer();//中央当年支出下级

        StringBuffer zysnzckm = new StringBuffer();//中央上年支出科目
        StringBuffer zysnzckm2 = new StringBuffer();//中央上年支出科目

        StringBuffer zysnzcxj = new StringBuffer();//中央上年支出下级
        StringBuffer zysnzcxj2 = new StringBuffer();//中央上年支出下级

        StringBuffer zysnjzhpjekm = new StringBuffer();//中央上年支结转核批金额科目
        StringBuffer zysnjzhpsyjekm = new StringBuffer();//中央上年结转核批剩余金额科目

        StringBuffer zysnjzhpjexj = new StringBuffer();//中央上年支结转核批金额下级
        StringBuffer zysnjzhpsyjexj = new StringBuffer();//中央上年结转核批剩余金额下级

        StringBuffer fzysnjzhpje = new StringBuffer();//非中央上年结转核批金额
        StringBuffer fzysnjzhpsyje = new StringBuffer();//非中央上年结转核批剩余金额

        StringBuffer fzysnjzhpjexm = new StringBuffer();//非中央上年结转核批金额项目
        StringBuffer fzysnjzhpsyjexm = new StringBuffer();//非中央上年结转核批剩余金额项目

        Map<String,Object> snXjMap = new HashMap<>();
        Map<String,Object> dnXjMap = new HashMap<>();

        //记录id 用作为sql条件
        List<String> fzyConditionId = new ArrayList<>();
        List<String> fzyxmConditionId = new ArrayList<>();
        List<String> zyConditionIdKm = new ArrayList<>();
        List<String> zyConditionIdXj = new ArrayList<>();
        //0,10_1:100
        if (!snData.isEmpty()){ //判断上年数据是否存在
            for (Map.Entry<String, Object> entry : snData.entrySet()) {
                String[] srly = entry.getKey().split(",");// 0,10_1:100
                if (srly[0].equals("0")) { //判断是否为中央
                    String[] srid = srly[1].split(":")[0].split("_");// 0,10_1:100
                    if (srid[0].equals(YJ)){ //科目级
                        /*zysnzckm.append(" when id = " + srid[1] + " then jzsyje - " + entry.getValue() + " ");
                        zysnzckm2.append(" when id = " + srid[1] + " then jzyyje + " + entry.getValue() + " ");*/
                        zysnzckm.append(" when id = " + srid[1] + " then yqndyjjzje - (yqndyjjzyyje + "+entry.getValue()+" ) ");
                        zysnzckm2.append(" when id = " + srid[1] + " then yqndyjjzyyje + " + entry.getValue() + " ");
                        zysnjzhpjekm.append(" when id = " + srid[1] + " and snjzhpje is null then " + entry.getValue() + " else snjzhpje + "+entry.getValue()+" ");
                        zysnjzhpsyjekm.append(" when id = " + srid[1] + " and snjzhpsyje is null then " + entry.getValue() + " else snjzhpsyje + "+entry.getValue()+" ");
                        zyConditionIdKm.add(srid[1]);
                    }else if (srid[0].equals(XJ)){ //下级
                        /*zysnzcxj.append(" when id = " + srid[1] + " then jzsyje - " + entry.getValue() + " ");
                        zysnzcxj2.append(" when id = " + srid[1] + " then jzyyje + " + entry.getValue() + " ");*/
                        zysnzcxj.append(" when id = " + srid[1] + " then yqndyjjzje - (yqndyjjzyyje + "+entry.getValue()+" ) ");
                        zysnzcxj2.append(" when id = " + srid[1] + " then yqndyjjzyyje + " + entry.getValue() + " ");
                        zysnjzhpjexj.append(" when id = " + srid[1] + " and snjzhpje is null then " + entry.getValue() + " else snjzhpje + "+entry.getValue()+" ");
                        zysnjzhpsyjexj.append(" when id = " + srid[1] + " and snjzhpsyje is null then " + entry.getValue() + " else snjzhpsyje + "+entry.getValue()+" ");
                        zyConditionIdXj.add(srid[1]);
                        snXjMap.put(srid[1],entry.getValue());
                    }
                }else{ //非中央
                    String[] srid = srly[1].split(":")[0].split("_");// 0,10_1:100
                    if (srid.length==1){ //类别
                        String fzyflId = srly[1].split(":")[0].split("_")[0];
                        String fzyId = VerificationDBUtil.getFzyIdByFlid(dw, fzyflId);
                        /*fzysnzc.append(" when id = " + fzyId + " then jzsyje - " + entry.getValue() + " ");
                        fzysnzc2.append(" when id = " + fzyId + " then jzyyje + " + entry.getValue() + " ");*/
                        fzysnzc.append(" when id = " + fzyId + " then yqndyjjzje - (yqndyjjzyyje + "+entry.getValue()+") ");
                        fzysnzc2.append(" when id = " + fzyId + " then yqndyjjzsyje + " + entry.getValue() + " ");
                        fzysnjzhpje.append(" when id = " + fzyId + " and snjzhpje is null then " + entry.getValue() + " else snjzhpje + "+entry.getValue()+" ");
                        fzysnjzhpsyje.append(" when id = " + fzyId + " and  snjzhpsyje is null then " + entry.getValue() + " else snjzhpsyje + "+entry.getValue()+" ");
                        fzyConditionId.add(fzyId);
                    }else if(srid.length==2){ //项目
                        String fzyxmId = srly[1].split(":")[0].split("_")[1];
                        fzysnxmzc.append(" when id = " + fzyxmId + " then yqndyjjzje - (yqndyjjzyyje + "+entry.getValue()+") ");
                        fzysnxmzc2.append(" when id = " + fzyxmId + " then yqndyjjzsyje + " + entry.getValue() + " ");
                        fzysnjzhpjexm.append(" when id="+fzyxmId+" and snjzhpje is null then " + entry.getValue() + " else snjzhpje + "+entry.getValue()+" ");
                        fzysnjzhpsyjexm.append(" when id="+fzyxmId+" and snjzhpsyje is null then " + entry.getValue() + " else snjzhpsyje + "+entry.getValue()+" ");
                        fzyxmConditionId.add(fzyxmId);
                    }
                }
            }
        }else{
            s1 = true;
        }

        if (!dnData.isEmpty()){ //判断本年数据是否存在
            for (Map.Entry<String, Object> entry : dnData.entrySet()) {//0,1:100
                String[] srly = entry.getKey().split(",");
                System.out.println("本年数据不存在："+srly.toString());
                if (srly[0].equals("0")) { //判断是否为中央
                    String[] srid = srly[1].split(":")[0].split("_");
                    if (srid[0].equals(YJ)){ //科目级
                        zydnzckm.append(" when id = " + srid[1] + " then yjsrsy - " + entry.getValue() + " ");
                        zydnzckm2.append(" when id = " + srid[1] + " then yhpje + " + entry.getValue() + " ");
                        zydnzckm3.append(" when id = " + srid[1] + " then hpsyje + " + entry.getValue() + " ");
                        zyConditionIdKm.add(srid[1]);
                    }else if (srid[0].equals(XJ)){ //下级
                        zydnzcxj.append(" when id = " + srid[1] + " then yjsrsy - " + entry.getValue() + " ");
                        zydnzcxj2.append(" when id = " + srid[1] + " then yhpje + " + entry.getValue() + " ");
                        zydnzcxj3.append(" when id = " + srid[1] + " then yhpsy + " + entry.getValue() + " ");
                        zyConditionIdXj.add(srid[1]);
                        dnXjMap.put(srid[1],entry.getValue());
                    }
                }else{ //非中央
                    String[] srid = srly[1].split(":")[0].split("_");// 0,10_1:100
                    if (srid.length==1) { //类别
                        String fzyflId = srly[1].split(":")[0].split("_")[0];
                        String fzyId = VerificationDBUtil.getFzyIdByFlid(dw, fzyflId);
                        fzydnzc.append(" when id = " + fzyId + " then yjsrsy - " + entry.getValue() + " ");
                        fzydnzc2.append(" when id = " + fzyId + " then yhpje + " + entry.getValue() + " ");
                        fzydnzc3.append(" when id = " + fzyId + " then hpsyje + " + entry.getValue() + " ");
                        fzyConditionId.add(fzyId);
                    }else if(srid.length==2) { //项目
                        String fzyxmId = srly[1].split(":")[0].split("_")[1];
                        fzydnxmzc.append(" when id = " + fzyxmId + " then yjsrsy - " + entry.getValue() + " ");
                        fzydnxmzc2.append(" when id = " + fzyxmId + " then yhpje + " + entry.getValue() + " ");
                        fzydnxmzc3.append(" when id = " + fzyxmId + " then hpsyje + " + entry.getValue() + " ");
                        fzyxmConditionId.add(fzyxmId);
                    }
                }
            }
        }else{
            s2 = true;
        }

        try {
            String zyKmSql = VerificationDBUtil.setupKm(zydnzckm, zysnzckm,zydnzckm2, zysnzckm2,zydnzckm3,zyConditionIdKm,zysnjzhpjekm,zysnjzhpsyjekm);
            if (!zyKmSql.isEmpty()){
                logger.info("预算编制扣减执行扣减科目sql----:"+zyKmSql);
                sql1 = rst.executeUpdate(zyKmSql);
            }else{
                sql1 = true;
            }
            String zyXjSql = VerificationDBUtil.setupXj(zydnzcxj, zysnzcxj,zydnzcxj2, zysnzcxj2, zyConditionIdXj,zysnjzhpjexj,zysnjzhpsyjexj);
            if (!zyXjSql.isEmpty()){
                if (snXjMap.isEmpty())
                    sql2 = true;

                for (Map.Entry<String,Object> entry:snXjMap.entrySet()) {  //扣减上年
                    List<String> superiorId = TreeStuctureDBUtil.getSuperiorId(Integer.valueOf(entry.getKey()));
                    String joinId = Joiner.on(",").join((Iterable<?>) superiorId);
//                    String sql = VerificationDBUtil.joinXjSql(joinId, entry.getValue().toString(), "jzsyje","jzyyje");
                    String sql = VerificationDBUtil.joinXjSql(joinId, entry.getValue().toString(), "yqndyjjzsyje","yqndyjjzyyje",0);
                    logger.info("预算编制扣减执行扣减下级金额，同时扣减所有上级金额(上年)sql----:"+sql);
                    sql2 = rst.executeUpdate(sql);  //扣减下级金额，同时扣减所有上级金额
                    if (!sql2){
                        break;
                    }
                    if (sql2){
//                        String kmsql = VerificationDBUtil.joinKmsql(entry.getKey(), "jzsyje","jzyyje", entry.getValue().toString());
                        String kmsql = VerificationDBUtil.joinKmsql(entry.getKey(), "yqndyjjzsyje","yqndyjjzyyje", entry.getValue().toString(),0);
                        logger.info("预算编制扣减执行扣减科目金额(上年)sql----:"+kmsql);
                        sql2 = rst.executeUpdate(kmsql);//扣减科目金额
                        if (!sql2){
                            break;
                        }
                    }
                }

                if (sql2){
                    for (Map.Entry<String,Object> entry:dnXjMap.entrySet()) {  //扣减本年
                        List<String> superiorId = TreeStuctureDBUtil.getSuperiorId(Integer.valueOf(entry.getKey()));
                        String joinId = Joiner.on(",").join((Iterable<?>) superiorId);
                        String sql = VerificationDBUtil.joinXjSql(joinId, entry.getValue().toString(), "yjsrsy","yhpje",1);
                        logger.info("预算编制扣减执行扣减下级金额，同时扣减所有上级金额(本年)sql----:"+sql);
                        sql2 = rst.executeUpdate(sql); //扣减下级金额，同时扣减所有上级金额
                        if (!sql2){
                            break;
                        }
                        if (sql2){
                            String kmsql = VerificationDBUtil.joinKmsql(entry.getKey(), "yjsrsy","yhpje", entry.getValue().toString(),1);
                            logger.info("预算编制扣减执行扣减科目金额(本年)sql----:"+kmsql);
                            sql2 = rst.executeUpdate(kmsql);//扣减科目金额
                            if (!sql2){
                                break;
                            }
                        }
                    }
                }
//                    sql2 = rst.executeUpdate(zyXjSql);
            }else{
                sql2 = true;
            }

            String fzySql = VerificationDBUtil.setupFzy(fzydnzc, fzysnzc,fzydnzc2, fzysnzc2,fzydnzc3,fzyConditionId,fzysnjzhpje,fzysnjzhpsyje);
            if (!fzySql.isEmpty()){
                logger.info("预算编制扣减执行扣减非中央收入sql----:"+fzySql);
                sql3 = rst.executeUpdate(fzySql);
            }else{
                sql3 = true;
            }

            String fzyxmSql = VerificationDBUtil.setupFzyxm(fzydnxmzc, fzysnxmzc, fzydnxmzc2, fzysnxmzc2,fzydnxmzc3,fzyxmConditionId,fzysnjzhpjexm,fzysnjzhpsyjexm);
            if (!fzyxmSql.isEmpty()){
                logger.info("预算编制扣减执行扣减非中央项目sql----:"+fzyxmSql);
                sql4 = rst.executeUpdate(fzyxmSql);

                if(sql4){
                    logger.info("扣减所属项目所在收入分类额度sql----：");
                }
            }else{
                sql4 = true;
            }

        } catch (Exception e) {
            e.printStackTrace();
            rst.rollback();
        }

        if (sql1 && sql2 && sql3 && sql4){
            rst.commit();
            return SUCCESS;
        }else{
            rst.rollback();
            requestInfo.getRequestManager().setMessagecontent("扣减金额错误！");
            requestInfo.getRequestManager().setMessageid("1");
            return FAILURE_AND_CONTINUE;
        }
    }
}
